package com.api.sdk;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;

public class ApiFieldProcess {

    public ArrayList<Field> getApiFields(Class<?> clazz) {
        Field[] fields = clazz.getDeclaredFields();
        ArrayList<Field> arrayList = new ArrayList<>();
        for (Field field : fields) {
            ApiField annotation = field.getAnnotation(ApiField.class);
            if (annotation != null) {
                arrayList.add(field);
            }
        }
        return arrayList;
    }

    //TODO 给这个方法加一个备用方法
    public Object getFieldValue(Object obj, String fieldName) {
        try {
            return obj.getClass().getDeclaredMethod("get" + fieldName.substring(0, 1).toUpperCase() +
                    fieldName.substring(1)).invoke(obj);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public void setFieldValue(Object obj, String fieldName, Object value) {
        try {
            obj.getClass().getDeclaredMethod("set" + fieldName.substring(0, 1).toUpperCase() +
                    fieldName.substring(1), value.getClass()).invoke(obj, value);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

}
